// pages/addDevice/addDevice.js
import * as api from '../../utils/api.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    brandList: [],
    modelList: [],
    brandId: 0,
    modelId: 0,
    brandIndex: 0,
    modelIndex: 0,
  },
  bindPickerChange(e) {
    const brandIndex = e.detail.value
    const brandId = this.data.brandList[brandIndex]['id']
    this.setData({
      brandIndex,
      brandId
    })
    this.getModelList(brandId)
  },
  bindsetChange(e){
    const modelIndex = e.detail.value
    const modelId = this.data.modelList[modelIndex]['id']
    this.setData({
      modelIndex,
      modelId
    })
  },

  submit() {
    const that = this
    api.customerAddProduct(this.data.brandId, this.data.modelId)
      .then(res => {
        if (res.code == 1) {
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          })
          setTimeout(that.toMyDevicePage, 1500)
        }
      }).catch(err => {
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })
  },

  toMyDevicePage() {
    wx.navigateTo({
      url: '/pages/myinfo/mydevice',
    })
  },

  getBrandList(){
    const that = this
    api.installBrandList()
      .then(res => {
        const brandList = res.data
        const brandId = brandList ? brandList[0]['id'] : 0;
        that.setData({
          brandList,
          brandId
        })
        return brandId
      }).then(brandId => {
        this.getModelList(brandId)
      }).catch(err => console.log(err))
  },

  getModelList(brandId = 0){
    const that = this
    api.installModelList(brandId ? brandId : that.data.brandId)
      .then(res => {
        const modelList = res.data
        const modelId = modelList ? modelList[0]['id'] : 0;
        const modelIndex = 0
        that.setData({
          modelList,
          modelId,
          modelIndex
        })
      }).catch(err => console.log(err))
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getBrandList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})